import React, {useEffect, useRef} from 'react';
import {Navigation, NavigationFunctionComponent} from 'react-native-navigation';
import {
  useNavigationComponentDidAppear,
  useNavigationComponentDidDisappear,
} from 'react-native-navigation-hooks';
import {
  View,
  Image,
  ScrollView,
  RefreshControl,
  BackHandler,
  NativeEventSubscription,
} from 'react-native';
import styled from 'styled-components/native';
import {
  Text,
  Button,
  Focusable,
  Container,
  Flex,
  FmButton,
  MyLikeButton,
  RankButton,
  RecommendPlaylist,
  Musicing,
} from '../components';
import SplashScreen from 'react-native-splash-screen';

import {observer} from 'mobx-react';

import {useGlobal, usePlayer} from '../hooks/useStores';
import TrackPlayer, {State} from 'react-native-track-player';
import usePlaybackState from '../hooks/usePlaybackState';

const Header = styled.View`
  margin: 15px 0px;
  height: 60px;
  width: 100%;
  padding: 0px 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
`;

const Logo = styled.Image`
  height: 60px;
  width: 250px;
  margin-right: auto;
`;

const Avatar = styled.View`
  height: 40px;
  width: 40px;
  border-radius: 40px;
  overflow: hidden;
`;

const Title = styled(Flex)`
  border-left-width: 4px;
  border-left-color: #e70625;
  padding-left: 8px;
  margin: 24px 4px;
  justify-content: space-between;
  align-items: center;
`;

interface Props {}
const Home: NavigationFunctionComponent<Props> = observer(({componentId}) => {
  const {
    logined,
    profile,
    loadUserInfo,
    loadMyPlaylist,
    loadRecommendPlaylist,
  }: any = useGlobal();

  const backHanlder = useRef<NativeEventSubscription>();
  const backTimer = useRef<number>(0);
  const {loadFm, current} = usePlayer();
  const playerState = usePlaybackState();

  const goLoginPage = () => {
    Navigation.push(componentId, {
      component: {name: 'Login'},
    });
  };

  const goMy = () => {
    Navigation.push(componentId, {
      component: {name: 'My'},
    });
  };

  const goRank = () => {
    Navigation.push(componentId, {
      component: {name: 'Rank'},
    });
  };

  const goCategory = () => {
    Navigation.push(componentId, {
      component: {name: 'Category'},
    });
  };

  const showMusicPage = () => {
    Navigation.push(componentId, {
      component: {name: 'Music'},
    });
  };

  useEffect(() => {
    loadUserInfo();
    SplashScreen.hide();
  }, [loadUserInfo]);

  useNavigationComponentDidDisappear(() => {
    backHanlder.current && backHanlder.current.remove();
  }, componentId);

  useNavigationComponentDidAppear(() => {
    backHanlder.current = BackHandler.addEventListener(
      'hardwareBackPress',
      () => {
        const now = new Date().valueOf();
        if (now - backTimer.current > 2000) {
          global.showToast({
            title: '再次按下返回键退出',
            icon: 'none',
          });
        } else {
          TrackPlayer.destroy();
          BackHandler.exitApp();
        }
        backTimer.current = now;
        return true;
      },
    );
  }, componentId);

  const [refreshing, setRefreshing] = React.useState(false);

  const onRefresh = React.useCallback(async () => {
    setRefreshing(true);
    await loadFm();
    await loadMyPlaylist();
    await loadRecommendPlaylist();
    setRefreshing(false);
  }, [setRefreshing, loadFm, loadMyPlaylist, loadRecommendPlaylist]);

  return (
    <View>
      <ScrollView
        refreshControl={
          <RefreshControl
            tintColor="#e70625"
            colors={['#e70625']}
            refreshing={refreshing}
            onRefresh={onRefresh}
          />
        }>
        <Header>
          <Logo resizeMode="contain" source={require('../assets/logo-w.png')} />
          {playerState === State.Playing || playerState === State.Paused ? (
            <Focusable
              onPress={showMusicPage}
              shadow={false}
              radius={40}
              style={{marginRight: 12}}>
              <Flex align="center">
                <Button
                  width={40}
                  height={40}
                  radius={40}
                  style={{marginRight: 6}}>
                  <Musicing width={20} height={20} />
                </Button>
                <Text
                  size={12}
                  style={{maxWidth: 180, marginRight: 24}}
                  numberOfLines={1}>
                  {current?.name || ''}
                </Text>
              </Flex>
            </Focusable>
          ) : null}

          {logined ? (
            <Focusable
              shadow={false}
              onPress={goMy}
              radius={30}
              style={{marginRight: 12}}>
              <Button>
                <Text>我的歌单</Text>
              </Button>
            </Focusable>
          ) : null}

          {logined ? (
            <Focusable radius={40} onPress={goLoginPage}>
              <Avatar>
                <Image
                  source={{uri: profile?.avatarUrl, width: 40, height: 40}}
                  resizeMode="contain"
                />
              </Avatar>
            </Focusable>
          ) : (
            <Focusable shadow={false} onPress={goLoginPage} radius={30}>
              <Button>
                <Text>登录</Text>
              </Button>
            </Focusable>
          )}
        </Header>

        <Container>
          <Flex style={{width: '100%'}} justify="space-between">
            <FmButton showMusicPage={showMusicPage} />
            <MyLikeButton componentId={componentId} />
            <RankButton onPress={goRank} />
          </Flex>

          <Title>
            <Text size={24}>推荐歌单</Text>

            <Focusable shadow={false} onPress={goCategory} radius={30}>
              <Button>
                <Text>更多歌单</Text>
              </Button>
            </Focusable>
          </Title>
          <RecommendPlaylist componentId={componentId} />
        </Container>
      </ScrollView>
    </View>
  );
});

Home.options = {
  topBar: {
    visible: false,
  },
};

export default Home;
